import { asyncRoutes, constantRoutes } from '../../router/router'

// function hasPermission(roles, route) {
//     if (route.meta && route.meta.roles) {
//       return roles.some(role => route.meta.roles.includes(role))
//     } else {
//       return true
//     }
//   }

//   export function filterAsyncRoutes(routes, roles) {
//     const res = []

//     routes.forEach(route => {
//       const tmp = { ...route }
//       if (hasPermission(roles, tmp)) {
//         if (tmp.children) {
//           tmp.children = filterAsyncRoutes(tmp.children, roles)
//         }
//         res.push(tmp)
//       }
//     })

//     return res
//   }
let tempRouters;

export function filterRouters(routers, roles, tempRouters) {
  routers.forEach((router, i) => {
    if (!router.children) {
      if (router.meta && router.meta.title) {
        let isDel = true;
        roles.forEach(item => {
          if (item.menuName === router.meta.title) {
            isDel = false;
          }
        })
        if (isDel) {
          //console.log("删除的节点：",router.meta.title)
        } else {
          //tempRouters[i]=router
          tempRouters.push(router)
        }
      }
    } else {
      // tempRouters.push({})
      const { children, ...other } = router
      const obj = { ...other, "children": [] }
      //  tempRouters[i]=other
      //  tempRouters[i].children=[]
      tempRouters.push(obj)
      filterRouters(children, roles, obj.children)
      // filterRouters(children,roles,tempRouters[i].children)
    }
  })
}

function deleteNullNode(routes) {
  routes.forEach((router, i) => {
    if (router.children) {
      deleteNullNode(router.children)
      if (router.children.length === 0) {
        routes.splice(i, 1)
      } else {
      }
    }
  })
}

const state = {
  routes: [],
  addRoutes: []
}

const mutations = {
  SET_ROUTES: (state, routes) => {
    state.addRoutes = routes
    state.routes = constantRoutes.concat(routes)
  },
  RESET_ROUTES:(state)=>{
    state.routes=[];
    state.addRoutes=[];
  }
}

const actions = {
  generateRoutes({ commit }, data) {
    return new Promise(resolve => {
      let accessedRoutes
      if (data.userInfo.roles==="Admin") {
        accessedRoutes = asyncRoutes || []
      } else {
        commit('RESET_ROUTES')
        tempRouters=[];
        filterRouters(asyncRoutes, data.pagePermission,tempRouters)
        deleteNullNode(tempRouters)
        accessedRoutes=tempRouters;
        
      }
      commit('SET_ROUTES', accessedRoutes)
      resolve(accessedRoutes)
    })
  }
}

export default {
  namespaced: true,
  state,
  mutations,
  actions
}